package com.pxmeta.app.controller.user;
import com.pxmeta.app.controller.user.utils.IdentificationUtils;
import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.pxmeta.common.constant.HttpStatus;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.core.redis.RedisCache;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.user.entity.UserIdentify;
import com.pxmeta.user.service.IUserStudentService;
import com.pxmeta.verify.entity.StuIdentifyVO;
import com.pxmeta.verify.entity.StuInfo;
import com.pxmeta.verify.entity.UserReal;
import com.pxmeta.verify.entity.dto.RealPersonVerifyDTO;
import com.pxmeta.verify.entity.dto.StudentVerifyDTO;
import com.pxmeta.verify.service.IUserRealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/identification")
@RequiredArgsConstructor
@Api(value = "用户身份认证", tags = "用户身份认证")
@Slf4j
public class IdentificationController {

    private final IUserStudentService userStudentService;
    private final RedisCache redisCache;
    private final IUserRealService userRealService;

    public static final String BAIDU_KEY = "baidu_access_key";


    @SaCheckLogin
    @ApiOperation(value = "学生认证（提交验证码）")
    @GetMapping("/student/identifyByCode")
    public AjaxResult identifyEducation( @RequestParam String code,
                                         @RequestParam(required = false) String schoolName) {
        StuInfo info;
        try {
            info = IdentificationUtils.parseUrl(code);
        } catch (Exception e) {
            return AjaxResult.error("认证失败，请检查验证码是否正确！");
        }
        if (info == null) {
            return AjaxResult.error("认证失败，没有查到学生信息！");
        }
        Long userId = SecurityUtils.getUserId();
        userStudentService.saveStudent(userId, info);
        return AjaxResult.success("认证成功！");
    }


    @ApiOperation(value = "学生认证（提交资料）")
    @SaCheckLogin
    @PostMapping("/student/identifyByImg")
    public AjaxResult identifyEducationByImg(@RequestBody StudentVerifyDTO dto) {
        List<String> imgUrls = dto.getImgUrls();
        if (imgUrls.size() > 3) {
            return AjaxResult.error(HttpStatus.PARAMS_ERROR, "图片数量超出限制！");
        }
        String orgName = dto.getOrgName();
        Long userId = SecurityUtils.getUserId();
        userStudentService.identifyByImg(userId, imgUrls,orgName);
        return AjaxResult.success();
    }


    @ApiOperation(value = "查询审核状态")
    @SaCheckLogin
    @GetMapping("/student/getIdentifyStatus")
    public AjaxResult<StuIdentifyVO> getIdentifyStatus() {
        Long userId = SecurityUtils.getUserId();
        UserIdentify userIdentify = userStudentService.getIdentifyStatus(userId);
        StuIdentifyVO vo = new StuIdentifyVO();

        UserReal userReal = userRealService.getById(userId);
        if (null != userReal){
            vo.setRealName(userReal.getRealName());
        }
        if (userIdentify==null){
            vo.setStatus(-2);
        }else {
            vo.setVerifyType(userIdentify.getIdType());
            vo.setStatus(userIdentify.getStatus());
            vo.setOrgName(userIdentify.getOrgName());
            vo.setReason(userIdentify.getReason());
        }
        return AjaxResult.success(vo);
    }


    @ApiOperation("实名认证")
    @SaCheckLogin
    @PostMapping("/realPerson/identify")
    public AjaxResult realPersonIdentify(@RequestBody @Valid RealPersonVerifyDTO dto) throws IOException {
        Long userId = SecurityUtils.getUserId();
        String realName = dto.getRealName();
        String idCard = dto.getIdCard();
        boolean verify = userRealService.verify(userId, realName, idCard);
        if (!verify) {
            return AjaxResult.error(HttpStatus.PARAMS_ERROR,"身份认证失败！");
        }
        return AjaxResult.success();
    }


    @ApiOperation("获取百度AccessToken")
    @SaCheckLogin
    @GetMapping("/getBaiduAccessToken")
    public AjaxResult getBaiduAccessToken() {
        Integer expires = null;
        String accessToken = redisCache.getCacheObject(BAIDU_KEY);
        if (StringUtils.isBlank(accessToken)) {
            String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=meiIqxffM8mR4axO1E3AVvnd&client_secret=t51CqX7vyhC9t9kibBaljGNughOG3Pes";
            RestTemplate restTemplate = new RestTemplate();
            JSONObject obj = restTemplate.getForObject(url, JSONObject.class);
            accessToken = obj.getString("access_token");
            expires = obj.getInteger("expires_in");
            redisCache.setCacheObject(BAIDU_KEY, accessToken, expires, TimeUnit.SECONDS);
        }
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("accessToken", accessToken);
        map.put("expires", expires);
        return AjaxResult.success();
    }


}
